/*
 * 项   目：learn-jwt
 * 作   者：LuoYiMin
 * 邮   箱：1725990142@qq.com
 * 创建时间：2018/12/7 9:49
 */
package com.roin.learn.jwt;

import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * jwt身份验证过滤器
 */
public class JWTFilter extends GenericFilterBean {
    public static final String LOGIN_USER_INFO_KEY="login_user_info";
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String authHeader = request.getHeader("Authorization");
        if (authHeader==null || !authHeader.startsWith("Bearer "))
            throw new ServletException("Missing or invalid Authorization header.");
        //去掉Bearer 部分，得到token
        String token = authHeader.substring(7);
        try {
            User user = TokenManager.parseJWT(token,User.class);
            //将对象传递给下一个请求
            request.setAttribute(LOGIN_USER_INFO_KEY, user);
        }catch (ExpiredJwtException e){
            throw new ServletException("token Expired.");
        }catch (Exception e){
            throw new ServletException("Expired token.");
            //TODO 这里可以构建response信息，告知用户重新登录
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
